import * as React from "react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";

interface Option {
  value: string;
  label: string;
}

interface MultiSelectProps {
  options: Option[];
  selectedOptions?: string[];
  onSelectionChange?: (values: string[]) => void;
}

const MultiSelect: React.FC<MultiSelectProps> = ({
  options,
  selectedOptions = [],
  onSelectionChange,
}) => {
  const [selectedValues, setSelectedValues] = React.useState(selectedOptions);
  const [filterValue, setFilterValue] = React.useState("");

  const handleOptionSelect = (value: string) => {
    if (selectedValues.includes(value)) {
      setSelectedValues(selectedValues.filter((v) => v !== value));
    } else {
      setSelectedValues([...selectedValues, value]);
    }
    if (onSelectionChange) {
      onSelectionChange([...selectedValues, value]);
    }
  };

  const filteredOptions = options.filter((option) =>
    option.label.toLowerCase().includes(filterValue.toLowerCase())
  );

  const renderSelectedValues = () => {
    if (selectedValues.length === 0) {
      return "Select values";
    }
    if (selectedValues.length === 1) {
      return (
        options.find((opt) => opt.value === selectedValues[0])?.label || ""
      );
    }
    if (selectedValues.length > 1) {
      return `${selectedValues.length} selected`;
    }
    return "";
  };

  return (
    <div className="relative">
      <Select onValueChange={() => {}}>
        <Input
          placeholder="Search option..."
          value={filterValue}
          onChange={(event) => setFilterValue(event.target.value)}
        />
        <SelectTrigger className="w-[180px]">
          <SelectValue placeholder={renderSelectedValues()} />
        </SelectTrigger>
        <SelectContent>
          {filteredOptions.map((option) => (
            <SelectItem
              key={option.value}
              value={option.value}
              onSelect={() => handleOptionSelect(option.value)}
            >
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
};

export default MultiSelect;
